#include "customthread.h"
#include "funcmgr.h"

void InitThread::run()
{
    QString ConnIp = ServerIpNet;
    quint16 ConnPort = 10085;

    QString HostName = ConnIp;
    if (!sFunc->IpAddrIsNet(HostName))
    {
        QHostInfo QInfo = QHostInfo::fromName(HostName);
        ConnIp = QInfo.addresses().first().toString();
    }

    emit SendMainConfig(ConnIp, ConnPort);
}

WorkObject::WorkObject(QObject *parent) : QObject(parent)
{

}

WorkObject::~WorkObject()
{
    if (HttpFile)
    {
        delete HttpFile;
        HttpFile = Q_NULLPTR;
    }
}

void WorkObject::WorkStart()
{
    //qDebug() << "WorkObject = " << QThread::currentThreadId();

    QString NowMd5 = sFunc->GetFileHashMd(LocalFilePath);
    if (NowMd5 == OMd5)
    {
        emit EmitCheckMd5Yes();
        return;
    }

    HttpFile = new QFile(LocalFilePath);
    if (!HttpFile->open(QIODevice::WriteOnly))
    {
        delete HttpFile;
        HttpFile = Q_NULLPTR;
        emit EmitNotOpenFile();
        return;
    }

    emit EmitBeginHttpTimer();

    QNetworkAccessManager* Manager = new QNetworkAccessManager(this);
    WorkReply = Manager->get(QNetworkRequest(QUrl(URL)));

    //下载出错信号
    QObject::connect(WorkReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(OnHttpError(QNetworkReply::NetworkError)));
    //下载进度信号
    QObject::connect(WorkReply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(HttpProgress(qint64, qint64)));
    //数据写入信号
    QObject::connect(WorkReply, SIGNAL(readyRead()), this, SLOT(HttpDowloading()));
    //请求完成信号
    QObject::connect(WorkReply, SIGNAL(finished()), this, SLOT(HttpDowloadFinished()));
}

void WorkObject::OnHttpError(QNetworkReply::NetworkError Error)
{
    WorkReply->close();
    WorkReply->deleteLater();

    if (HttpFile)
    {
        HttpFile->close();
        delete HttpFile;
        HttpFile = Q_NULLPTR;
    }
    emit EmitWorkError(Error);
}

void WorkObject::HttpProgress(qint64 NowLen, qint64 FileLen)
{
    emit EmitWorkProgress(NowLen, FileLen);
}

void WorkObject::HttpDowloading()
{
    if (HttpFile)
    {
        HttpFile->write(WorkReply->readAll());
    }
}

void WorkObject::HttpDowloadFinished()
{
    WorkReply->close();
    WorkReply->deleteLater();

    if (HttpFile)
    {
        //将缓冲区数据刷新
        HttpFile->flush();
        HttpFile->close();
        delete HttpFile;
        HttpFile = Q_NULLPTR;
    }

    emit EmitWorkFinished();
}
